require('./src/db')
var  ArticleBasic = require('./src/model/ArticleBasic')
var  UserBasic = require('./src/model/UserBasic')
var  ArticleInfo  = require('./src/model/ArticleInfo')
var  Channels = require('./src/model/Channels')
var fs = require('fs')
var address = require('./address')

let idList = []
// 随机生成文章中的图片数据
const createArticleImage = async () => {
  console.log("当前的变量" + process.env.MODEL)
   // 初始化一个进度条长度为 50 的 ProgressBar 实例
    var pb = new ProgressBar('生产进度', 0);
    console.log("开始生产文章数据！")
    const list = await ArticleBasic.find({  }).lean()
    const timeStamp = new Date('2019-03-11 09:00:00').getTime()
    list.forEach(async (item, index) => {
       const cover = createMathImage()
       const channel_id = await createTempChannel()
      
       const update_time = timeStamp + index
       await  ArticleBasic.findByIdAndUpdate(item._id, { ...item, channel_id, cover, update_time, user_id: 1111, create_time: '2019-03-11 09:00:00'})
       pb.render({ completed: index + 1, total: list.length })
       if (index === (list.length - 1)) {
         pb.clear()
         console.log('生产文章数据结束')
         process.exit() // 退出进程
       }
    })
  }
  const updateUserPhoto = async () => {
    const addressPath = process.env.AddressType == 1 ? address.address : `${address.host}:${address.port}`
    console.log("开始更新用户基本数据")
    const list = await UserBasic.find({  }).lean()
    list.forEach(async item => {
       await  UserBasic.findByIdAndUpdate(item._id, { ...item, profile_photo: `http://${addressPath}/images/user_head.jpg`})
       console.log(`更新当前用户数据成功`)
    })
  }
  // 删除没用的文章标题
  const  delOtherArticleContent = async () => {
    console.log("开始处理文章详情数据")
    const list = await ArticleBasic.find({  }).lean()
    const articleContent = await ArticleInfo.find({  }).lean()
    articleContent.forEach(async (item, index) => {
      console.log(`开始处理文章${index + 1}, id为：${item.article_id}`)
      const isExit = list.findIndex(obj => obj.article_id === item.article_id)
      console.log(`对比结果是:` + isExit)
        if (isExit === -1) {
          // 如果找不到
          await ArticleInfo.deleteOne(item)
          console.log('删除一个多余的文章详情')
        }
    })
  }
  // 删除没用的文章基本数据
  const  delOtherArticleBasic = async () => {
    console.log("开始处理文章基本数据")
    const list = await ArticleBasic.find({  }).lean()
    const articleContent = await ArticleInfo.find({  }).lean()
    list.forEach(async (item, index) => {
      console.log(`开始处理文章${index + 1}, id为：${item.article_id}`)
      const isExit = articleContent.findIndex(obj => obj.article_id === item.article_id)
      console.log(`对比结果是:` + isExit)
        if (isExit === -1) {
          // 如果找不到
          await ArticleBasic.deleteOne(item)
          console.log('删除一个多余的文章基本数据')
        }
    })
  }
  
  // 创建临时图片
  const createMathImage = () => {
    const addressPath = process.env.AddressType == 1 ? address.address : `${address.host}:${address.port}`

     let imageCount = random(0,3) 
     imageCount = imageCount === 2 ? 3 : imageCount 
     var imageList = []
     for (let index = 0; index < imageCount; index++) {
      imageList.push(`http://${addressPath}/resources/images/${random(1,100)}.jpg`)
     }
     return imageList.join(',')
  }
  // 生成临时频道
  const createTempChannel = async () => {
    if (!idList.length) {
       // 如果
       await getChannelList()
    }
    const index = random(0, idList.length)
    const  channel_id = idList[index]
    idList.splice(index, 1)
    return channel_id
  }
  function random(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
  }
 
  const  getChannelList = async () => {
     idList =  (await  Channels.find({ }).lean()).map(item => item.channel_id)
  }
  // createArticleImage() // 更新文章封面
  // updateUserPhoto() // 更新用户头像
  // delOtherArticleContent() // 删除多余文章详情
  // delOtherArticleBasic()

  var slog = require('single-line-log').stdout;

// 封装的 ProgressBar 工具
function ProgressBar(description, bar_length){
  // 两个基本参数(属性)
  this.description = description || 'Progress';       // 命令行开头的文字信息
  this.length = bar_length || 25;                     // 进度条的长度(单位：字符)，默认设为 25

  // 刷新进度条图案、文字的方法
  this.render = function (opts){
    var percent = (opts.completed / opts.total).toFixed(4);    // 计算进度(子任务的 完成数 除以 总数)
    var cell_num = Math.floor(percent * this.length);             // 计算需要多少个 █ 符号来拼凑图案

    // 拼接黑色条
    var cell = '';
    for (var i=0;i<cell_num;i++) {
      cell += '█';
    }

    // 拼接灰色条
    var empty = '';
    for (var i=0;i<this.length-cell_num;i++) {
      empty += '░';
    }

    // 拼接最终文本
    var cmdText = this.description + ': ' + (100*percent).toFixed(2) + '% ' + cell + empty + ' ' + opts.completed + '/' + opts.total;
    
    // 在单行输出文本
    slog(cmdText);
  };
  this.clear = function () {
    slog('')
  }
}
function delDir(path){
  let files = [];
  if(fs.existsSync(path)){
      files = fs.readdirSync(path);
      files.forEach((file, index) => {
          let curPath = path + "/" + file;
          if(fs.statSync(curPath).isDirectory()){
              delDir(curPath); //递归删除文件夹
          } else {
              fs.unlinkSync(curPath); //删除文件
          }
      });
      fs.rmdirSync(path);
  }
}
function createDir (path) {
  fs.mkdirSync(path)
}
  module.exports = { 
    createArticleImage,
    updateUserPhoto,
    delOtherArticleContent,
    delOtherArticleBasic,
    delDir,
    createDir
  }
